#ifndef _THREAD_HPP_
#define _THREAD_HPP_

#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

//    V 1
namespace ThreadModule
{
    enum class TSTATUS
    {
        NEW,//新建
       RUNNING,//启动
        STOP//停止
    };

    using func_t = std::function<void(std::string name)>;
    static int number = 1;

    class Thread
    {
    private:
        //int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
        //                 void *(*start_routine) (void *), void *arg);
        //成员变量，第一个参数是this，这样编不过，需加上static
        static void * Routine(void *args)
        {
            //static_cast：在c++用于类型转换
            Thread *t = static_cast<Thread *>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func(t->Name());
            return nullptr;
        }
        //开启分离
        void EnableDetach(){ _joinable = false;}
        
    public :
        Thread(func_t func)
        :_func(func)
        ,_status(TSTATUS::NEW)
        ,_joinable(true)
        {
            _name = "Thread-"+std::to_string(number++);
            _pid = getpid();
        }
        ~Thread()
        {}
        //启动
        bool Start()
        {
            if(_status != TSTATUS::RUNNING)
            {
                //创建线程，创建好了就是启动的状态
                int n = ::pthread_create(&_tid,nullptr,Routine,this);
                if(n != 0) return false;
                return true;
            }
            return false;
        }
        //等待
        bool Join()
        {
            if(_joinable)
            {
                int n = ::pthread_join(_tid,nullptr);
                if(n != 0) return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;

        }

        bool Stop()
        {
            if(_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if(n != 0) return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;

        }

        //分离
        void Detach()
        {
            EnableDetach();
            ::pthread_detach(_tid);
        }
        std::string Name(){ return _name; }
        //是否被分离
        bool IsJoinable(){ return _joinable; }
        
    private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable;//是否是分离的，默认不是
        func_t _func;
        TSTATUS _status;//线程状态
    };
}

#endif